/**
 * @Company 青鸟软通   
 * @Title: ExamUserService.java 
 * @Package  com.jbinfo.qingcaowan.exam.service.impl
 * @author lizhenwei   
 * @date 2016年07月31日  12:50:22
 * @version V1.0   
 */
package com.jbinfo.qingcaowan.exam.service.impl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jbinfo.common.utils.UUIDUtils;
import com.jbinfo.qingcaowan.common.BusinessException;
import com.jbinfo.qingcaowan.common.CheckParamUtil;
import com.jbinfo.qingcaowan.common.ClonePojoUtil;
import com.jbinfo.qingcaowan.common.ExceptionConstants.BusinessExceptionCode;
import com.jbinfo.qingcaowan.exam.dao.ChooseAnswerDao;
import com.jbinfo.qingcaowan.exam.dao.ExamUserDao;
import com.jbinfo.qingcaowan.exam.dao.QuestionDao;
import com.jbinfo.qingcaowan.exam.dto.ExamCircleDTO;
import com.jbinfo.qingcaowan.exam.dto.ExamQuestionDTO;
import com.jbinfo.qingcaowan.exam.dto.ExamUserDTO;
import com.jbinfo.qingcaowan.exam.entity.ExamChooseAnswer;
import com.jbinfo.qingcaowan.exam.entity.ExamQuestion;
import com.jbinfo.qingcaowan.exam.entity.ExamUserDomain;
import com.jbinfo.qingcaowan.exam.service.ExamScoreService;
import com.jbinfo.qingcaowan.exam.service.ExamUserService;

/** 
 * @ClassName: ExamUserService
 * @Description: ExamUser的Service接口定义类
 *  
 */
@Service("examUserService")
public class ExamUserServiceImpl implements ExamUserService{

	private static final Logger LOG = LoggerFactory.getLogger(ExamUserServiceImpl.class);
	
	/** 
	* @Fields examUserDao : ExamUserDao 工具依赖 
	*/
	@Resource(name="examUserDao")
	private ExamUserDao examUserDao;
	
	@Resource(name="questionDao")
	private QuestionDao questionDao;
	
	@Resource(name="chooseAnswerDao")
	private ChooseAnswerDao chooseAnswerDao;
	
	@Resource
	private ExamScoreService examScoreService;
	
	/*===============业务方法=============*/
	
	// 保存用户答题信息\如果该题是最后一题，则返回考试得分
	@Override
	public Object saveExamUser(ExamUserDTO examUserDTO) {
		
		CheckParamUtil.checkFieldIfNotBlank(examUserDTO, 
				"userId", "questionId","userAnswer","examCircle");
		
		// 查询该题是否作答过
		List<ExamUserDomain> examUserList = examUserDao.findExamUser(examUserDTO);
		
		if (examUserList != null && !examUserList.isEmpty()) {
			// 此题已作答过
			throw new BusinessException(BusinessExceptionCode.database_duplicate_data, "此题已作答过！");
		}
		ExamUserDomain entity = ClonePojoUtil.copyClassFromTo(examUserDTO, ExamUserDomain.class);
		entity.setId(UUIDUtils.create());
		// 添加考试编码
		entity.setExamCircle(examUserDTO.getExamCircle());
		
		ExamChooseAnswer examChooseAnswer = new ExamChooseAnswer();
		examChooseAnswer.setQuestionId(examUserDTO.getQuestionId());
		// 试题分单选题，多选题，判断题
		String userAnswer = examUserDTO.getUserAnswer();// 用户答案
		
		// 用户此题答案
		List<String> userAnswerList = new ArrayList<String>();
		
		if (userAnswer.contains(",")) {
			// 如果用户答案包含"," 则是多选题
			String [] answerCodes = userAnswer.split(",");
			userAnswerList = Arrays.asList(answerCodes);
		} else {
			// 单选题或判断题
			userAnswerList.add(userAnswer);
		}
		// 根据questionId 查询试题类型  
		ExamQuestion question = questionDao.selectQuestionById(examUserDTO.getQuestionId());
		examChooseAnswer.setQuestionType(question.getType());
		// 查询正确答案
		List<ExamChooseAnswer> rightAnswerList = chooseAnswerDao.selectTrueAnswer(examChooseAnswer);
		List<String> okAnswerList = new ArrayList<String>();
		for (ExamChooseAnswer chooseAnswer: rightAnswerList) {
			// 如果是判断题，则取isTrue
			if (chooseAnswer.getQuestionType().equals("2")) {
				okAnswerList.add(chooseAnswer.getIsTrue());
			} else {
				okAnswerList.add(chooseAnswer.getAnswerCode());
			}
		}
		
		Integer userScore = Integer.valueOf(0);
		
		// 判断用户答案是否正确
		boolean bSame = CollectionUtils.isEqualCollection(userAnswerList, okAnswerList);
		
		//如果答案正确，则该题试题分数即为用户此题得分
		if (true == bSame) {
			
			String id = examUserDTO.getQuestionId();
			
			if (id == null || id.equals("")) {
				throw new BusinessException(BusinessExceptionCode.param_error, "试题ID不能为空!");
			}
			//
//			ExamQuestion examQuestion = questionDao.selectQuestionById(id);
//			userScore = examQuestion.getQuestionScore();
			// 根据 t_exam_ship 中考试编码、试题Id 查询此题分数
			userScore = questionDao.findQuestionScoreByCode(examUserDTO);
			
			LOG.info("userScore: " + userScore.toString());
		}
		
		entity.setUserScore(userScore);
		
		examUserDao.save(entity);
		
		// 查询最后一题
		
		ExamQuestionDTO queryDTO = new ExamQuestionDTO();
		queryDTO.setExamCircle(examUserDTO.getExamCircle());
		
		String questionId = questionDao.selectLastQuestion(queryDTO);
		
		// 如果试题为最后一题，则传出考试得分
		ExamCircleDTO dto = new ExamCircleDTO();
		
		if (examUserDTO.getQuestionId().equals(questionId)) {
			// 获取用户得分
			ExamCircleDTO examCircleDTO = new ExamCircleDTO();
			examCircleDTO.setUserId(examUserDTO.getUserId());
			examCircleDTO.setExamCircle(examUserDTO.getExamCircle());
			dto = (ExamCircleDTO) examScoreService.findExamScore(examCircleDTO);
			
			//dto = examCircleJson.getResultBean();
		}
		return dto;
	}

	// 查看用户试题答案内容集答案分析
	@Override
	public Object findExamUserAndAnaly(ExamUserDTO queryDTO) {
		ExamUserDTO dto = new ExamUserDTO();
		
		List<ExamUserDTO> examUserList = examUserDao.findExamUserScore(queryDTO);
		
		// 如果是多选题，答案返回List
		List<String> userAnswerList = new ArrayList<String>();
		
		if (examUserList != null && !examUserList.isEmpty()) {
			
			ExamUserDTO examUser = examUserList.get(0);
			dto = ClonePojoUtil.copyClassFromTo(examUser, ExamUserDTO.class);
			
			if (examUser != null && examUser.getType() != null) {
				if (examUser.getType().equals("1")) {
					if (examUser.getUserAnswer().contains(",")) {
						String [] userAnswers = examUser.getUserAnswer().split(",");
						userAnswerList = Arrays.asList(userAnswers);
					} else {
						userAnswerList.add(examUser.getUserAnswer());
					}
				} else {
					userAnswerList.add(examUser.getUserAnswer());
				}
			}
			
			dto.setUserAnswerList(userAnswerList);
		}
		
		return dto;
	}

	
}
